import 'package:black_movice/utils/Utils.dart';
import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class VideoPlayer extends StatefulWidget {
  final String videoUrl;
  const VideoPlayer({super.key, required this.videoUrl});

  @override
  State<VideoPlayer> createState() => _VideoPlayerState();
}

class _VideoPlayerState extends State<VideoPlayer> {
  // 播放控制器
  late VideoPlayerController _videoPlayerController;
  //chewie控制器
  late ChewieController _chewieController;
  // loading
  late bool _loading = true;
  int? bufferDelay = 1;
  Future<void> initVideo() async {
    setState(() {
      _loading = true;
    });
    _videoPlayerController =
        VideoPlayerController.contentUri(Uri.parse(widget.videoUrl));
    _videoPlayerController.initialize().then((_) {
      _chewieController =
          ChewieController(videoPlayerController: _videoPlayerController);
      _initChewitController();
      setState(() {
        _loading = false;
      });
    });
  }

  void _initChewitController() {
    try {
      _chewieController = ChewieController(
        videoPlayerController: _videoPlayerController,
        autoPlay: true,
        progressIndicatorDelay:
            bufferDelay != null ? Duration(milliseconds: bufferDelay!) : null,
      );
    } catch (e) {
      Utils.logError(e);
    }
  }

  @override
  void initState() {
    super.initState();
    initVideo();
  }

  @override
  void dispose() {
    // 释放资源
    super.dispose();
    _videoPlayerController.dispose();
    _chewieController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.black,
      child: _loading
          ? const Center(
              child: CircularProgressIndicator(),
            )
          : Center(
              child: AspectRatio(
                aspectRatio: _videoPlayerController.value.aspectRatio,
                child: Chewie(controller: _chewieController),
              ),
            ),
    );
  }
}
